import { PlusOutlined } from '@ant-design/icons'
import {
  Col,
  Row,
  Flex,
  Typography,
  Button,
  Input,
  Form,
  Table,
  Alert,
  Switch,
  message,
  Select,
  Tag,
  Modal
} from 'antd'
import React, { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
// 修改导入语句确保使用正确的API
import {
  adminCouponList,
  adminCouponEdit,
  adminCouponStatusAPI,
  adminCouponDelete,
  adminCouponStatus
} from '../service/activaty'
import moment from 'moment' // 添加moment导入

function MarketCoupon() {
  const navigate = useNavigate()
  const [couponList, setCouponList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [condition, setCondition] = useState({})
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 用于更新列表
  const [refreshTrigger, setRefreshTrigger] = useState(0)

  // 获取优惠券列表
  const loadCouponList = async () => {
    try {
      const res = await adminCouponList({
        ...condition,
        coupon_status: 1,  // 添加coupon_status为1的筛选条件
        pageNo,
        pageSize: 10
      })
      
      if (res.data && res.data.objects) {
        // 处理每个优惠券的状态
        const processedCoupons = res.data.objects.map(coupon => {
          // 计算当前状态
          const now = moment()
          const startDate = moment(coupon.startDate)
          const endDate = moment(coupon.endDate)
          
          let status = coupon.status // 保留后端返回的状态
          
          // 前端覆盖计算状态（如果需要）
          if (now.isBefore(startDate)) {
            status = 0 // 未开始
          } else if (now.isAfter(endDate)) {
            status = 2 // 已结束
          } else {
            status = 1 // 进行中
          }
          
          return {
            ...coupon,
            status
          }
        })
        
        setCouponList(processedCoupons)
        setTotal(res.data.total)
      }
    } catch (error) {
      console.error('获取优惠券列表失败:', error)
      message.error('获取优惠券列表失败，请稍后重试')
    }
  }

  // 删除优惠券
  const handleDelete = async (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除优惠券"${record.couponName}"吗？`,
      onOk: async () => {
        try {
          // 使用专门的删除API
          const res = await adminCouponDelete(record.id)

          if (res.code === '0') {
            message.success('优惠券删除成功')
            setRefreshTrigger(refreshTrigger + 1)
          } else {
            message.error('优惠券删除失败：' + (res.msg || '未知错误'))
          }
        } catch (error) {
          console.error('删除优惠券失败:', error)
          message.error('删除优惠券失败，请稍后重试')
        }
      }
    })
  }
  

  // 切换优惠券启用状态
  const handleStatusChange = async (record, checked) => {
    try {
      // 修改为正确的函数名
      const res = await adminCouponStatus({
        id: record.id,
        enableStatus: checked ? 1 : 0
      })
      
      if (res.code === '0') {
        message.success(checked ? '优惠券已启用' : '优惠券已停用')
        setRefreshTrigger(refreshTrigger + 1)
      } else {
        message.error(checked ? '启用失败' : '停用失败')
      }
    } catch (error) {
      console.error('更新优惠券状态失败:', error)
      message.error('更新优惠券状态失败，请稍后重试')
    }
  }
  
  // 监听刷新触发器和页码变化
  useEffect(() => {
    loadCouponList()
  }, [refreshTrigger, pageNo])
  
  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>优惠券管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/admin/market/addCoupon')}
            >
              新建优惠券
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form
            layout="inline"
            onFinish={async (values) => {
              setCondition({
                couponName: values.couponName,
                couponType: values.couponType !== '0' ? values.couponType : '',
                status: values.status !== '0' ? values.status : ''
              })
              setRefreshTrigger(refreshTrigger + 1)
            }}
          >
            <Form.Item label="优惠券名称" name="couponName">
              <Input placeholder="请输入优惠券名称" />
            </Form.Item>
            <Form.Item
              label="优惠券类型"
              name="couponType"
              initialValue={'0'}
            >
              <Select
                options={[
                  { value: '0', label: '全部' },
                  { value: '1', label: '满减' },
                  { value: '2', label: '折扣' },
                  { value: '3', label: '随机' }
                ]}
                style={{ width: 200 }}
              />
            </Form.Item>
            <Form.Item label="优惠券状态" name="status" initialValue={'0'}>
              <Select
                options={[
                  { value: '0', label: '全部' },
                  { value: '1', label: '未开始' },
                  { value: '2', label: '进行中' },
                  { value: '3', label: '已结束' }
                ]}
                style={{ width: 200 }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      {/* 表格 */}
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            优惠券列表
          </Typography.Paragraph>
          {hasSelected && (
            <Alert
              message={`已经选择 ${selectedRowKeys.length} 项`}
              type="info"
              showIcon
            />
          )}
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              total,
              defaultCurrent: 1,
              onChange: async (page) => {
                setPageNo(page)
              }
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (newSelectedRowKeys) => {
                setSelectedRowKeys(newSelectedRowKeys)
              }
            }}
            dataSource={couponList}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '优惠券名称',
                dataIndex: 'couponName',
                key: 'couponName'
              },
              {
                title: '适用范围',
                dataIndex: 'applicable',
                key: 'applicable'
              },
              {
                title: '优惠内容',
                dataIndex: 'describes',
                key: 'describes'
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (_, record) => {
                  switch (record.status) {
                    case 0:
                      return <Tag color="blue">未开始</Tag>
                    case 1:
                      return <Tag color="green">进行中</Tag>
                    case 2:
                      return <Tag color="red">已结束</Tag>
                    default:
                      return <Tag color="blue">未开始</Tag>
                  }
                }
              },
              {
                title: '数量',
                dataIndex: 'usageNum',
                key: 'usageNum',
                render: (_, record) => {
                  return <>{record.usageNum}张</>
                }
              },
              {
                title: '有效期',
                dataIndex: 'startDate',
                key: 'startDate',
                render: (_, record) => {
                  return (
                    <>
                      {record.startDate.substring(0, 10)} -
                      {record.endDate.substring(0, 10)}
                    </>
                  )
                }
              },
              {
                title: '启用状态',
                dataIndex: 'enableStatus',
                key: 'enableStatus',
                render: (_, record) => {
                  return (
                    <Switch 
                      checked={record.enableStatus === 1} 
                      onChange={(checked) => handleStatusChange(record, checked)}
                    />
                  )
                }
              },
              {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                align: 'center',
                render: (_, record) => {
                  return (
                    <span className="op">
                      <Link to={`/admin/market/editCoupon/${record.id}`}>
                        编辑
                      </Link>
                      <a 
                        style={{ marginLeft: 10 }}
                        onClick={() => handleDelete(record)}
                      >
                        删除
                      </a>
                    </span>
                  )
                }
              }
            ]}
          />
        </Col>
      </Row>
    </>
  )
}

export default MarketCoupon